import { getData } from '@vimi/utils-api'
import { cascaderTree } from '@vimi/utils-tool'

const state = {
  productCategory: [],
  productCategoryTree: [],
}

const getters = {
  productCategory: state => state.productCategory,
  productCategoryTree: state => state.productCategoryTree,
}

const actions = {
  async getProductCategory({ commit }, force = false) {
    if (!force && state.productCategory.length) {
      return Promise.resolve(state.productCategory)
    }

    await getData('industrial_db', 'enum_category', {
      'id.endlike': '10',
      'is_hide.eq': '0',
    }).then(res => {
      const data = (res && res.data) || []
      const tree =
        cascaderTree({
          data,
          structure: [2, 2, 2, 3, 3],
        })?.[0]?.children ?? []

      commit('productCategory', data)
      commit('productCategoryTree', tree)

      return data
    })
  },
}

const mutations = {
  productCategory: (state, payload) => (state.productCategory = payload),
  productCategoryTree: (state, payload) => (state.productCategoryTree = payload),
}

export default {
  state,
  getters,
  actions,
  mutations,
}
